# -*- coding: utf-8 -*-
import redis
import time,random
import atx,pymysql
import traceback
from multiprocessing import Pool
import logging
from email.header import Header
from email.mime.text import MIMEText
from email.utils import parseaddr, formataddr
import smtplib


logger = logging.getLogger('mylogger')
logger.setLevel(logging.DEBUG)
fh = logging.FileHandler('test.log')
ch = logging.StreamHandler()
ch.setLevel(logging.DEBUG)
formatter = logging.Formatter('%(asctime)s - %(process)d - %(levelname)s - %(message)s')
fh.setFormatter(formatter)
ch.setFormatter(formatter)
logger.addHandler(fh)
logger.addHandler(ch)

def _format_addr(s):
    name, addr = parseaddr(s)
    return formataddr(( \
        Header(name, 'utf-8').encode(), \
        addr.encode('utf-8') if isinstance(addr, unicode) else addr))



def send_email(addr,text):
    from_addr = 'ysmlfx@163.com'
    password = 'qweasdzxc123'
    to_addr = addr
    smtp_server = 'smtp.163.com'
    msg = MIMEText(text, 'plain', 'utf-8')
    msg['From'] = _format_addr('姚航 <%s>' % from_addr)
    msg['To'] = _format_addr('陈吉全 <%s>' % to_addr)
    msg['Subject'] = Header('支付宝余额不足', 'utf-8').encode()
    server = smtplib.SMTP(smtp_server,25,timeout=10)
    server.set_debuglevel(0)
    server.login(from_addr, password)
    server.sendmail(from_addr, [to_addr], msg.as_string())
    server.quit()





def listen_task(prot):
    drive = atx.connect(prot)
    drive.start_app("com.sunrise.scmbhc", "com.sunrise.scmbhc.ui.activity.loading.LoadingActivity")

    drive(textContains = u'跳过').click()
    logger.info(u'%s -- APP已启动，等待订单中....' % prot)


    rcon = redis.StrictRedis(host=u'localhost')
    queue = u'yaohang'
    logger.debug(u'%s成功连接redis'%prot)


    logger.debug(u'%s成功连接mysql'%prot)

    while True:
        logger.debug(u'%s成功进入监听状态' % prot)
        task = rcon.blpop(queue)
        info = eval(task[1])
        logger.info(u"获取到新订单---%s" % info)

        phone_number = info['phone_number']
        money = info['money']
        ID = info['ID']

        logger.info(u'%s开始充值' % prot)
        drive(textContains=u'充值95').click()
        logger.debug(u'%s点击充值' % prot)
        drive(text=u'输入充值号码').set_text(phone_number)
        logger.debug(u'%s输入号' % prot)
        drive(text=u'其他\n输入10的整数倍').click()
        logger.debug(u'%s点击金额输入' % prot)
        drive(text=u'10-500').set_text(money)
        logger.debug(u'%s输入金额' % prot)
        drive(resourceId=u'com.sunrise.scmbhc:id/item_pay_mode_parent').sibling(index=1).click()  # done
        logger.debug(u'%s选择支付宝付款' % prot)
        drive(resourceId=u'com.sunrise.scmbhc:id/btn_right').click()  # 点击确认支付

        if drive(resourceId=u'com.sunrise.scmbhc:id/btn_right').wait.gone(timeout=1000): #判断付款的按钮是否消失

            if drive(text=u"付款详情").exists:
                logger.debug('执行到第一个判断')
                paid = drive(textContains=u'元').info['text'].encode('utf-8')
                account = drive(textContains=u'***').info['text'].encode('utf-8')

                if drive(text=u'确认付款').exists:

                    drive(text=u'确认付款').click()
                    for i in 'asdqwe':
                        drive(text=i).click()
                    drive(text=u'付款').click()

                    mobile_order_id = long(
                        drive(resourceId='com.sunrise.scmbhc:id/tv_success_order_id').info['text'].encode('utf-8'))

                    if '成功' in drive(resourceId='com.sunrise.scmbhc:id/tv_order_confirm').info['text'].encode(
                            'utf-8'):  # 判断是否支付成功
                        logger.info(u"充值成功---%s " % info)
                        result = u'success'

                    else:
                        logger.warning(u"充值失败---%s" % info)
                        result = u'failure'

                    sql = '''INSERT INTO Recharge_record(order_id,phone_number,money,result,mobile_order_id,paid,account,date) VALUES (%s,%d,%d,'%s',%d,%s,'%s',now())''' % (
                        ID, phone_number, money, result, mobile_order_id, str(paid.replace('元', '')), account)
                    try:
                        db = pymysql.connect('localhost', 'root', 'qweasdzxc', 'test', charset='utf8')
                        cursor = db.cursor()
                        cursor.execute(sql)
                        db.commit()
                    except:
                        db.rollback()
                        logger.warning(u"订单数据写入失败---%s" % info)
                    db.close()
                    drive(resourceId='com.sunrise.scmbhc:id/order_btn_back').click()  # 返回的代码，暂时不要启用

                    logger.info(u'%s 正在等待新任务....' % prot)


                elif drive(text=u'使用新卡付款').exists:
                    logger.error('支付宝余额不足，请尽快补全..该号已被重新加入队列')
                    rcon.lpush('yaohang', info)

                    drive(className='android.widget.ImageView').click()
                    drive(text='返回充值页面').click()
                    drive(resourceId=u'com.sunrise.scmbhc:id/title_btn_back').click()
                    send_email('13666209137@139.com', '支付宝账号：%s余额不足，请尽快充值' % account)
                    logger.debug('通知邮件已发送')

            if drive(text=u"重试").exists:
                drive(text=u"重试").click()
                logger.debug('执行到第二个判断')
                if drive(text=u"付款详情").wait.exists():
                    paid = drive(textContains=u'元').info['text'].encode('utf-8')
                    account = drive(textContains=u'***').info['text'].encode('utf-8')

                    if drive(text=u'确认付款').exists:

                        drive(text=u'确认付款').click()
                        for i in 'asdqwe':
                            drive(text=i).click()
                        drive(text=u'付款').click()

                        mobile_order_id = long(
                            drive(resourceId='com.sunrise.scmbhc:id/tv_success_order_id').info['text'].encode('utf-8'))

                        if '成功' in drive(resourceId='com.sunrise.scmbhc:id/tv_order_confirm').info['text'].encode(
                                'utf-8'):  # 判断是否支付成功
                            logger.info(u"充值成功---%s " % info)
                            result = u'success'

                        else:
                            logger.warning(u"充值失败---%s" % info)
                            result = u'failure'

                        sql = '''INSERT INTO Recharge_record(order_id,phone_number,money,result,mobile_order_id,paid,account,date) VALUES (%s,%d,%d,'%s',%d,%s,'%s',now())''' % (
                            ID, phone_number, money, result, mobile_order_id, str(paid.replace('元', '')), account)
                        try:
                            db = pymysql.connect('localhost', 'root', 'qweasdzxc', 'test', charset='utf8')
                            cursor = db.cursor()
                            cursor.execute(sql)
                            db.commit()
                        except:
                            db.rollback()
                            logger.warning(u"订单数据写入失败---%s" % info)
                        db.close()
                        drive(resourceId='com.sunrise.scmbhc:id/order_btn_back').click()  # 返回的代码，暂时不要启用

                        logger.info(u'%s 正在等待新任务....' % prot)


                    elif drive(text=u'使用新卡付款').exists:
                        logger.error('支付宝余额不足，请尽快补全..该号已被重新加入队列')
                        rcon.lpush('yaohang', info)

                        drive(className='android.widget.ImageView').click()
                        drive(text='返回充值页面').click()
                        drive(resourceId=u'com.sunrise.scmbhc:id/title_btn_back').click()
                        send_email('13666209137@139.com', '支付宝账号：%s余额不足，请尽快充值' % account)
                        logger.debug('通知邮件已发送')


        else:
            logger.error(u'无法加载支付宝，可能号码有误或是网络故障 %s'%info)
            result = u'failure'
            paid = 0
            account = 'null'
            mobile_order_id = 0

            sql = '''INSERT INTO Recharge_record(order_id,phone_number,money,result,mobile_order_id,paid,account,date) VALUES (%s,%d,%d,'%s',%d,%s,'%s',now())''' % (
                ID, phone_number, money, result, mobile_order_id, paid, account)
            try:
                db = pymysql.connect('localhost', 'root', 'qweasdzxc', 'test', charset='utf8')
                cursor = db.cursor()
                cursor.execute(sql)
                db.commit()
            except:
                db.rollback()
                logger.warning(u"订单数据写入失败---%s" % info)
            db.close()
            drive(resourceId=u'com.sunrise.scmbhc:id/title_btn_back').click()

            logger.info(u'%s 正在等待新任务....' % prot)







if __name__ == '__main__':
    listen_task('b1566c857d43')



